package org.vgou.util;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.vgou.pojo.Email;

public class EmailTools {
	protected final Log logger = LogFactory.getLog(getClass());

	private static EmailTools instance = null;

	public static EmailTools getInstance() {
		if (instance == null)
			instance = new EmailTools();
		return instance;
	}

	/**
	 * 发送电子邮件
	 * 
	 * @param host
	 *            邮件服务器主机
	 * @param userName
	 *            发送用户名
	 * @param passWord
	 *            发送用户密码
	 * @param fromUser
	 *            发送用户EMAIL地址
	 * @param toUser
	 *            接受用户EMAIL地址
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @param html
	 *            邮件内容是否为HTML格式
	 * @return boolean
	 * @throws Exception
	 */
	public boolean sendMail(String host, String userName, String passWord,
			String fromUser, String toUser, String subject, String content,
			boolean html) throws Exception {
		boolean result = false;
		try {
			// 取得真正域名
			// String last_host = StringUtils.splitStr(host, ".", 1);

			JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
			// 设定 Mail Server
			senderImpl.setHost(host);

			// SMTP验证时，需要用户名和密码
			senderImpl.setUsername(userName);
			senderImpl.setPassword(passWord);

			Properties props = new Properties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.required", "true");

			Session session = Session.getDefaultInstance(props, null);
			senderImpl.setSession(session);

			/**
			 * props.put("mail.smtp.starttls.enable", "true"); // added this
			 * line props.put("mail.smtp.host", host);
			 * props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth",
			 * "true"); props.put("mail.smtp.starttls.required", "true"); //
			 * added this line
			 */
			if (html) {
				// 建立邮件讯息
				MimeMessage mailMessage = senderImpl.createMimeMessage();
				MimeMessageHelper messageHelper = new MimeMessageHelper(
						mailMessage);

				// 设定收件人、寄件人、主题与内文
				messageHelper.setTo(toUser);
				messageHelper.setFrom(fromUser);
				messageHelper.setSubject(subject);
				messageHelper.setText(content, true);

				// 传送邮件
				senderImpl.send(mailMessage);
			} else {

				// 建立邮件讯息
				SimpleMailMessage mailMessage = new SimpleMailMessage();

				// 设定收件人、寄件人、主题与内文
				mailMessage.setTo(toUser);
				mailMessage.setFrom(fromUser);
				mailMessage.setSubject(subject);
				mailMessage.setText(content);
				// 传送邮件
				senderImpl.send(mailMessage);
			}

			result = true;
		} catch (Exception e) {
			logger.error("邮件发送出错：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 直接从SPRING配置文件注入服务器相关信息后发送邮件
	 * 
	 * @param sender
	 *            发送类
	 * @param toUser
	 *            发送人
	 * @param fromUser
	 *            接收人
	 * @param subject
	 *            主题
	 * @param content
	 *            内容
	 * @throws Exception
	 */
	public void sendMail(JavaMailSender sender, String toUser, String fromUser,
			String subject, String content, boolean html) throws Exception {
		try {
//			logger.debug("发送邮件。");
			if (!html) {
				SimpleMailMessage mail = new SimpleMailMessage();
				mail.setTo(toUser); // 接收人
				mail.setFrom(fromUser);
				mail.setSubject(subject);
				logger.debug("接收人是:" + toUser);

				// 把模版内容写入邮件中
				mail.setText(content);
				sender.send(mail);
			} else {
				MimeMessage msg = sender.createMimeMessage();
				// 设置utf-8或GBK编码，否则邮件会有乱码，true表示为multipart邮件
				MimeMessageHelper helper = new MimeMessageHelper(msg, true,
						"utf-8");
				helper.setTo(toUser); // 邮件接收地址
				helper.setFrom(fromUser); // 邮件发送地址,这里必须和xml里的邮件地址相同一致
				helper.setSubject(subject); // 主题
				helper.setText(content, true); // 邮件内容，注意加参数true，表示启用html格式
				sender.send(msg); // 发送邮件
			}
			
		} catch (Exception e) {
			logger.error("发送EMAIL出错:" + e.getMessage());
		}
	}

	/**
	 * 批量发送邮件
	 * 
	 * @param sender
	 *            注入SPRING邮件服务类
	 * @param fromUser
	 *            发送用户
	 * @param subject
	 *            主题
	 * @param content
	 *            内容
	 * @param address
	 *            接收用户集合
	 * 
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("static-access")
	public void sendBatchEmail(JavaMailSender sender, String fromUser,
			String subject, String content, List<String> address)
			throws MessagingException, UnsupportedEncodingException {
		MimeMessage msg = sender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");

		String toList = getMailList(address);
		InternetAddress[] iaToList = new InternetAddress().parse(toList);
		msg.setRecipients(Message.RecipientType.TO, iaToList);
		helper.setFrom(fromUser);
		helper.setSubject(subject);
		helper.setText(content, true);

		sender.send(msg);
		System.out.println("sendBatchEmail OK");
	}

	/**
	 * 
	 * @param email
	 * 		邮件基本信息
	 * @param sender
	 * 		使用spring注入的邮件发送对象
	 */
	public void sendEmail(Email email,JavaMailSender sender){
		
	}
	
	/**
	 * 集合转换字符串
	 */
	public String getMailList(List<String> to) {
		StringBuffer toList = new StringBuffer();
		int length = to.size();
		if (to != null && length < 2) {
			toList.append(to.get(0));
		} else {
			for (int i = 0; i < length; i++) {
				toList.append(to.get(i));
				if (i != (length - 1)) {
					toList.append(",");
				}
			}
		}
		return toList.toString();
	}
}
